use std::{
    collections::HashMap,
    mem::MaybeUninit,
    sync::{Arc, Mutex},
};

use common::protocol::{get_version, XID};
use tracing::{debug, info, warn};

use crate::{
    net::{http_net::HttpNet, tcp_net::TCPNet},
    protocol::{self, protocol_handler::ProtocolHandler},
};

use super::{
    channel_manager::ChannelManager,
    dxc_manager::DXCManager,
    message_manager::{self, MessageManager},
};

pub trait AirportEventHandler {
    fn init(&self);

    fn start_airport(&self);

    fn start_from_watcher(&self);

    fn end_airport(&self);
}

pub struct Airport {
    // 网络
    pub xprc_net: Arc<Box<TCPNet>>,
    // http 服务器
    pub http_net: Arc<Box<HttpNet>>,
    // 协议处理器
    protocol_handlers: [MaybeUninit<Box<dyn ProtocolHandler>>; 256],
    protocol_handlers_init_array: [bool; 256],
    //
    // 消息管理器
    msg_manager: Arc<Box<MessageManager>>,
    //
    channel_manager: Arc<Box<ChannelManager>>,
    //
    dxc_manager: Arc<Box<DXCManager>>,
    // 所有请求待处理的函数都放在这里
    request_handle_map: Mutex<HashMap<XID, Box<dyn FnOnce(Vec<u8>) + Send + Sync>>>,
}

unsafe impl Send for Airport {}
unsafe impl Sync for Airport {}

impl Airport {
    pub fn new(xprc_net: Arc<Box<TCPNet>>, http_net: Arc<Box<HttpNet>>) -> Box<Airport> {
        Box::new(Airport {
            xprc_net: xprc_net,
            http_net: http_net,
            protocol_handlers_init_array: [false; 256],
            protocol_handlers: unsafe { MaybeUninit::uninit().assume_init() },
            msg_manager: Arc::new(Box::new(MessageManager::new())),
            channel_manager: Arc::new(Box::new(ChannelManager::new())),
            dxc_manager: Arc::new(Box::new(DXCManager::new())),
            request_handle_map: Mutex::new(HashMap::new()),
        })
    }

    // pub fn get_xprc_net(&self) -> Arc<Box<TCPNet>> {
    //     self.xprc_net.clone()
    // }

    // pub fn get_http_net(&self) -> Arc<Box<HttpNet>> {
    //     self.http_net.clone()
    // }

    pub fn get_message_manager(&self) -> Arc<Box<MessageManager>> {
        self.msg_manager.clone()
    }

    pub fn get_channel_manager(&self) -> Arc<Box<ChannelManager>> {
        self.channel_manager.clone()
    }

    pub fn get_dxc_manager(&self) -> Arc<Box<DXCManager>> {
        self.dxc_manager.clone()
    }

    pub fn add_request_handler(&self, xid: XID, handler: Box<dyn FnOnce(Vec<u8>) + Send + Sync>) {
        let mut request_handle_map = self.request_handle_map.lock().unwrap();

        request_handle_map.insert(xid, handler);
    }

    pub async fn response_message(&self, xid: XID, resp_message: Vec<u8>) {
        // 打包消息
        //
        let request_handler = {
            let mut request_handle_map = self.request_handle_map.lock().unwrap();
            request_handle_map.remove(&xid)
        };
        if request_handler.is_some() {
            let request_handler = request_handler.unwrap();
            (request_handler)(resp_message);
            return;
        }
        let channel_id = self.msg_manager.get_msg_from_channel_id(&xid).await;
        if channel_id.is_none() {
            debug!("返回信息 {} 的通道已经关闭", xid.request_id);
            return;
        }

        let mut channel_id = channel_id.unwrap();

        for _ in 0..3 {
            if self
                .send_message_to_channel(channel_id, &resp_message)
                .await
            {
                return;
            }

            if xid.conn_id == 0 {
                break;
            }

            let new_channel_id = self
                .get_channel_manager()
                .get_channel_by_conn_id(xid.conn_id)
                .await;

            if new_channel_id.is_none() {
                break;
            }
            channel_id = new_channel_id.unwrap();
        }
        info!("回复消息 {} 失败...", xid.request_id);
    }

    pub async fn message_in(&self, channel_id: i64, message: Vec<u8>) -> bool {
        let version = get_version(&message);

        let version = version & 255;

        if !self.protocol_handlers_init_array[version as usize] {
            warn!("获取不到版本为{}的协议处理器,丢弃消息...", version);
            return false;
        }
        //

        let protocol_handler: &MaybeUninit<Box<dyn ProtocolHandler>> =
            &self.protocol_handlers[version as usize];

        unsafe {
            protocol_handler
                .assume_init_ref()
                .handle_msg(self, channel_id, message)
                .await
        }
    }

    pub fn add_protocol_handler(&mut self, protocol_handler: Box<dyn ProtocolHandler>) -> bool {
        let version: u16 = protocol_handler.get_version();

        if self.protocol_handlers_init_array[version as usize] {
            warn!("添加版本{}处理器失败, 已经存在...", version);
            return false;
        }

        unsafe {
            self.protocol_handlers[version as usize]
                .as_mut_ptr()
                .write(protocol_handler);
        }

        self.protocol_handlers_init_array[version as usize] = true;

        info!("添加版本 {} 处理器成功...", version);
        true
    }

    pub async fn send_message(&self, message: Vec<u8>) -> bool {
        let version = get_version(&message);
        let version = version & 255;
        debug!("发送消息, 协议版本号：{}...", version);

        if self.protocol_handlers_init_array[version as usize] {
            warn!("获取不到版本为{}的协议处理器,丢弃消息...", version);
            return false;
        }

        let protocol_handler: &MaybeUninit<Box<dyn ProtocolHandler>> =
            &self.protocol_handlers[version as usize];
        // 发送消息
        unsafe {
            protocol_handler
                .assume_init_ref()
                .handle_msg(self, 0, message)
                .await;
        }
        true
    }
    /**
     * 发送给通道的，忽略即可
     */
    pub async fn send_message_to_channel(&self, channel_id: i64, message: &Vec<u8>) -> bool {
        let channel = self.channel_manager.get_channel(channel_id).await;
        if channel.is_none() {
            return false;
        }
        channel.unwrap().send_message(message).await
    }

    pub async fn send_msg_by_conn_id(
        &self,
        conn_id: i64,
        channel_id: i64,
        message: Vec<u8>,
    ) -> bool {
        let xid = protocol::get_xid(&message);

        if xid.is_none() {
            return false;
        }

        let message = Arc::new(message);

        let xid = xid.unwrap();

        self.msg_manager
            .add_message(channel_id, xid, message.clone())
            .await;

        self.dxc_manager
            .send_message_to_one_remote_dxc(conn_id, message.as_ref())
            .await;
        true
    }

    // pub async fn response_msg(&self, conn_id: i64, channel_id: i64) {}

    /**
     *
     */
    pub async fn close_channel(&self, channel_id: i64) {
        self.channel_manager.remove_channel(channel_id).await;
    }
    /**
     *
     */
    pub async fn get_channel_conn_id(&self, channel_id: i64) -> Option<i64> {
        let channel = self.channel_manager.get_channel(channel_id).await;
        if channel.is_none() {
            return None;
        }
        Some(channel.unwrap().conn_id())
    }

    pub async fn build_xprc_channel(&self, conn_id: i64) -> Option<i64> {
        self.xprc_net.connect_to(conn_id).await
    }
}
